package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.po.Emp;
import com.itheima.domain.po.OperateLog;
import com.itheima.domain.vo.PageResult;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class LogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements LogService {
    
    @Autowired
    private OperateLogMapper operateLogMapper;
    
    @Autowired
    private EmpMapper empMapper;
    
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize) {
        //使用MybatisPlus实现分页查询
        Page<OperateLog> pageInfo = Page.of(page, pageSize);
        operateLogMapper.selectPage(pageInfo, null);
        
        // 填充操作人姓名
        fillOperateEmpName(pageInfo.getRecords());
        
        return new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
    }
    
    /**
     * 填充操作人姓名
     * @param logs 日志列表
     */
    private void fillOperateEmpName(List<OperateLog> logs) {
        // 收集所有需要查询的员工ID
        List<Integer> empIds = logs.stream()
                .map(OperateLog::getOperateEmpId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());
        
        if (!empIds.isEmpty()) {
            // 批量查询员工信息
            List<Emp> empList = empMapper.selectBatchIds(empIds);
            
            // 获取ID对应的姓名
            Map<Integer, String> empNameMap = empList.stream()
                    .collect(Collectors.toMap(Emp::getId, Emp::getName));
            
            // 填充日志中的操作人姓名
            logs.forEach(log -> {
                if (log.getOperateEmpId() != null) {
                    log.setOperateEmpName(empNameMap.get(log.getOperateEmpId()));
                }
            });
        }
    }
}